package com.jianjun.project.monitor.logininfor;

import cn.hutool.core.convert.Convert;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jianjun.common.constant.HttpStatus;
import com.jianjun.framework.security.service.SysPasswordService;
import com.jianjun.framework.web.domain.AjaxResult;
import com.jianjun.framework.web.interceptor.DataScope;
import com.jianjun.framework.web.page.TableDataInfo;
import com.jianjun.framework.web.render.ExcelWriterRender;
import com.jianjun.project.common.model.SysLogininfor;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统访问记录
 *
 * @author source
 */
@Path(value = "/monitor/logininfor")
public class SysLogininforController extends Controller {
    @Inject
    SysLogininforService logininforService;
    @Inject
    SysPasswordService passwordService;

    @DataScope(permission = "monitor:logininfor:list")
    public void list() {
        SysLogininfor sysLogininfor = JsonKit.parse(getKv().toJson(), SysLogininfor.class);
        Page<SysLogininfor> page = logininforService.paginate(sysLogininfor);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getList());
        rspData.setTotal(page.getTotalRow());
        renderJson(rspData);
    }


    @DataScope(permission = "monitor:logininfor:export")
    public void export() {
        SysLogininfor sysLogininfor = JsonKit.parse(getKv().toJson(), SysLogininfor.class);
        List<SysLogininfor> list = logininforService.selectLogininforList(sysLogininfor);
        List<Map<String, Object>> mapList = list.stream().map(Model::toMap).collect(Collectors.toList());
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(mapList, true);
        render(new ExcelWriterRender(writer, sysLogininfor.getClass().getSimpleName()));
    }

    @DataScope(permission = "monitor:logininfor:remove")
    public void index() {
        renderJson(AjaxResult.ajax(logininforService.deleteLogininforByIds(Convert.toLongArray(getPara()))));
    }

    @DataScope(permission = "monitor:logininfor:remove")
    public void clean() {
        logininforService.cleanLogininfor();
        renderJson(AjaxResult.success());
    }


    @DataScope(permission = "monitor:logininfor:unlock")
    public void unlock() {
        String userName = getPara();
        passwordService.clearLoginRecordCache(userName);
        renderJson(AjaxResult.success());
    }
}
